<template>
  <view class="publish-container">
    <view class="header">
      <text class="title">发布跑腿任务</text>
    </view>
    
    <view class="form-container">
      <!-- 任务类型选择 -->
      <view class="form-item">
        <text class="label">任务类型</text>
        <picker @change="bindTypeChange" :value="typeIndex" :range="typeArray" range-key="name">
          <view class="picker" style="color: #737373;">
            {{ formData.type? typeArray[typeIndex].name : '请选择任务类型'}}
            <uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
          </view>
        </picker>
      </view>
      
      <!-- 任务标题 -->
      <view class="form-item">
        <text class="label">任务标题</text>
        <input class="input" v-model="formData.title" placeholder="请输入任务标题" />
      </view>
      
      <!-- 任务详情 -->
	  <view class="form-item">
	    <text class="label">选择院校</text>
	    <picker
	    			mode="selector" 
	    			:range="colleges" 
	    			:value="collegeIndex" 
	    			@change="onCollegeChange"
	    >
	    			<view class="picker-view" style="color: #737373;">
	    			  {{ colleges[collegeIndex] || '请选择学院' }}
	    			</view>
	    </picker>
	  </view>
	  <view class="form-item">
	    <text class="label">任务地点</text>
	    <textarea class="textarea" v-model="formData.address" placeholder="请输入地址" auto-height />
	  </view>
      <view class="form-item">
        <text class="label">任务详情</text>
        <textarea class="textarea" v-model="formData.remark" placeholder="请详细描述您的需求" auto-height />
      </view>
      
      <!-- 悬赏金额 -->
      <view class="form-item">
        <text class="label">悬赏金额</text>
        <view class="price-input">
          <text class="unit">¥</text>
          <input class="input" type="number" v-model="formData.price" placeholder="0.00" />
        </view>
      </view>
      
      <!-- 截止时间 -->
   <!--   <view class="form-item">
        <text class="label">截止时间</text>
        <picker mode="date" :value="formData.deadline" :start="startDate" :end="endDate" @change="bindDateChange">
          <view class="picker">
            {{formData.deadline || '请选择截止日期'}}
            <uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
          </view>
        </picker>
      </view>
      -->
      <!-- 联系方式 -->
      <view class="form-item">
        <text class="label">联系方式</text>
        <input class="input" v-model="formData.contact" placeholder="请输入手机号/QQ/微信" />
      </view>
      
     
	  <view class="media-uploader" style="margin-top: 25rpx;">
	    <view class="upload-tips">添加图片或视频（可选）</view>
	    <view class="media-list">
	      <!-- 已上传的媒体项 -->
	      <view 
	        class="media-item" 
	        v-for="(item, index) in mediaList" 
	        :key="index"
	      >
	        <image 
	          v-if="item.type === 'image'" 
	          class="media-preview" 
	          :src="item.url" 
	          mode="aspectFill"
	        ></image>
	        <video 
	          v-if="item.type === 'video'" 
	          class="media-preview" 
	          :src="item.url" 
	  		show-bottom-progress="false"
	  		show-center-play-btn="false"
	  		show-fullscreen-btn="false"
	          controls
	        ></video>
	        <view class="delete-btn" @click="removeMedia(index)">
	          <uni-icons type="closeempty" size="18" color="#fff"></uni-icons>
	        </view>
	      </view>
	      
	      <!-- 上传按钮 -->
	      <view 
	        class="upload-btn" 
	        v-if="mediaList.length < 9"
	        @click="showMediaPicker"
	      >
	        <uni-icons type="plusempty" size="32" color="#999"></uni-icons>
	      </view>
	    </view>
	  </view>
	  
    </view>
    
    <!-- 发布按钮 -->
    <view class="btn-container">
      <button class="publish-btn" @click="handlePublish">发布任务</button>
    </view>
	
	<!-- 媒体选择器 -->
	<uni-popup ref="mediaPicker" type="bottom">
	  <view class="media-picker-popup">
	    <view class="popup-title">选择媒体类型</view>
	    <view class="popup-options">
	      <view class="option-item" @click="chooseImage">
	        <uni-icons type="image" size="24" color="#FF5A5F"></uni-icons>
	        <text>图片</text>
	      </view>
	      <view class="option-item" @click="chooseVideo">
	        <uni-icons type="videocam" size="24" color="#FF5A5F"></uni-icons>
	        <text>视频</text>
	      </view>
	    </view>
	    <view class="cancel-btn" @click="closeMediaPicker">取消</view>
	  </view>
	</uni-popup>
  </view>
</template>
<script>
import { formatDate } from '@/utils/util.js';

export default {
  data() {
    const currentDate = formatDate(new Date(), 'yyyy-MM-dd');
    const endDate = new Date();
    endDate.setFullYear(endDate.getFullYear() + 1);
    
    return {
      typeArray: [],
      typeIndex: '',
	  mediaList:[],
	  collegeIndex:'',
	  colleges: [],
      formData: {
        type: '',
        title: '',
        remark: '',
        price: '',
        deadline: currentDate,
        contact: '',
        image: "",
		college:'',
		address:'',
		school_id:''
      },
      startDate: currentDate,
      endDate: formatDate(endDate, 'yyyy-MM-dd'),
	  lists:[]
    }
  },
  onLoad() {
  	this.getPaoType()
	this.getShool()
  },
  methods: {
	  async  getShool(){
	  	const res = await this.$api.get('/School/list')
	  	if(res.data.code === 200) {
			this.lists = res.data.data
	  		res.data.data.forEach(item => {
	  			this.colleges.push(item.school_name)
	  		})
	  	}
	  },
	  onCollegeChange(e) {
	    this.collegeIndex = e.target.value;
	    this.formData.college = this.colleges[this.collegeIndex];
		this.formData.school_id = this.lists[this.collegeIndex].school_id
		console.log('院校id',this.formData.school_id,this.formData.college)
	  },
	  // 显示媒体选择器
	  showMediaPicker() {
	    this.$refs.mediaPicker.open()
	  },
	  
	  // 关闭媒体选择器
	  closeMediaPicker() {
	    this.$refs.mediaPicker.close()
	  },
	  
	  // 选择图片
	  chooseImage() {
	    this.closeMediaPicker()
	    let that = this
	    uni.chooseImage({
	      count: 9 - this.mediaList.length, // 还能选择的数量
	      sizeType: ['compressed'], // 压缩图
	      sourceType: ['album', 'camera'], // 相册和相机
	      success:  (res) => {
	        // 添加到媒体列表
	        res.tempFiles.forEach((file) => {
	  		  this.$api.uploadFile('/upload/File',file.path).then(res => {
	  		    this.mediaList.push({
	  			  type: 'image',
	  			  url: res.data.cosUrl,
	  			})
	  		  })
	  		
	        })
	      }
	    })
	  },
	  
	  // 选择视频
	  chooseVideo() {
	    this.closeMediaPicker()
	    let that = this
	    uni.chooseVideo({
	      sourceType: ['album', 'camera'],
	      compressed: true,
	      // maxDuration: 60, // 60秒
	      success: (res) => {
	        // 视频只能选一个，先清空已有的
	  	  console.log('上传的图片地址',res)
	        this.mediaList = this.mediaList.filter(item => item.type !== 'video')
	  	  this.$api.uploadFile('/upload/File',res.tempFilePath).then(response => {
	  	    this.mediaList.push({
	  	      type: 'video',
	  	      url: response.data.cosUrl,
	  	      file: {
	  	        path: res.tempFilePath,
	  	        size: res.size,
	  	        duration: res.duration,
	  	        width: res.width,
	  	        height: res.height
	  	      }
	  	    })
	  	  })
	       
	        
	      }
	    })
	  },
	  
	  // 删除媒体
	  removeMedia(index) {
	    this.mediaList.splice(index, 1)
	  },
	  
    bindTypeChange(e) {
      this.typeIndex = e.detail.value;
      this.formData.type = this.typeArray[this.typeIndex].value;
    },
    bindDateChange(e) {
      this.formData.deadline = e.detail.value;
    },
   
	async getPaoType(){
		const res = await this.$api.get('/PaoType/list','',true)
		if(res.data.code === 200) {
			res.data.data.forEach(item => {
				this.typeArray.push({
					name:item.name,
					value:item.id
				})
			})
		}
	},
    // 发布任务
    async handlePublish() {
		
      if (!this.validateForm()) {
        return;
      }
      
      // uni.showLoading({
      //   title: '发布中...'
      // });
	  this.formData.image = JSON.stringify(this.mediaList)
      const res = await this.$api.post('/pao/create',this.formData,true)
	  if(res.data.code === 200) {
		 //跳转支付跑腿任务
		 uni.navigateTo({
		 	url:'/pagesA/paopayment?taskId='+res.data.data.task.id
		 })
	  }
     
    },
    // 表单验证
    validateForm() {
	  if(!this.formData.type){
		  uni.showToast({
		    title: '请选择跑腿类型',
		    icon: 'none'
		  });
		  return false;
	  }
      if (!this.formData.title) {
        uni.showToast({
          title: '请填写跑腿标题',
          icon: 'none'
        });
        return false;
      }
	  if(!this.formData.college){
		  uni.showToast({
		    title: '请选择院校',
		    icon: 'none'
		  });
		  return false;
	  }
	  if(!this.formData.address){
		  uni.showToast({
		    title: '请填写地址',
		    icon: 'none'
		  });
		  return false;
	  }
      
      if (!this.formData.remark) {
        uni.showToast({
          title: '请填写跑腿详情',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.price) {
        uni.showToast({
          title: '请设置跑腿悬赏金额',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.contact) {
        uni.showToast({
          title: '请填写联系方式',
          icon: 'none'
        });
        return false;
      }
      
      return true;
    }
  }
}
</script>
<style lang="scss" scoped>
	/* 媒体选择弹出层 */
	.media-picker-popup {
	  background-color: #fff;
	  border-radius: 30rpx 30rpx 0 0;
	  padding: 40rpx;
	}
	
	.popup-title {
	  font-size: 32rpx;
	  font-weight: bold;
	  text-align: center;
	  margin-bottom: 40rpx;
	  color: #333;
	}
	
	.popup-options {
	  display: flex;
	  justify-content: space-around;
	  margin-bottom: 40rpx;
	}
	
	.option-item {
	  display: flex;
	  flex-direction: column;
	  align-items: center;
	  font-size: 28rpx;
	  color: #333;
	}
	
	.option-item text {
	  margin-top: 15rpx;
	}
	
	.cancel-btn {
	  text-align: center;
	  font-size: 32rpx;
	  color: #FF5A5F;
	  padding: 30rpx 0;
	  border-top: 1rpx solid #eee;
	}
	/* 媒体上传区 */
	.media-uploader {
	  background-color: #fff;
	  margin-bottom: 30rpx;
	  padding-bottom: 30rpx;
	  // box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	.upload-tips {
	  font-size: 28rpx;
	  color: #999;
	  margin-bottom: 30rpx;
	}
	
	.media-list {
	  display: flex;
	  flex-wrap: wrap;
	  margin: -10rpx;
	}
	
	.media-item, .upload-btn {
	  width: 195rpx;
	  height: 195rpx;
	  margin: 10rpx;
	  position: relative;
	  border-radius: 12rpx;
	  overflow: hidden;
	  background-color: #f5f5f5;
	}
	
	.media-preview {
	  width: 100%;
	  height: 100%;
	}
	
	.delete-btn {
	  position: absolute;
	  right: 10rpx;
	  top: 10rpx;
	  width: 40rpx;
	  height: 40rpx;
	  border-radius: 50%;
	  background-color: rgba(0, 0, 0, 0.5);
	  display: flex;
	  align-items: center;
	  justify-content: center;
	}
	
	.upload-btn {
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  width: 190rpx;
	  height: 190rpx;
	  border: 2rpx dashed #ddd;
	}
	
.publish-container {
  padding: 20rpx 30rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
  
  .header {
    padding: 20rpx 0;
    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .form-container {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 0 30rpx;
    margin-top: 20rpx;
    
    .form-item {
      padding: 30rpx 0;
      border-bottom: 1rpx solid #f0f0f0;
      display: flex;
      flex-direction: column;
      
      &:last-child {
        border-bottom: none;
      }
      
      .label {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 20rpx;
      }
      
      .picker {
        font-size: 30rpx;
        color: #333;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      
      .input {
        font-size: 30rpx;
        height: 60rpx;
        color: #333;
      }
      
      .price-input {
        display: flex;
        align-items: center;
        
        .unit {
          font-size: 36rpx;
          color: #ff5a5f;
          margin-right: 10rpx;
        }
        
        .input {
          flex: 1;
        }
      }
      
      .textarea {
        font-size: 30rpx;
        width: 100%;
        min-height: 120rpx;
        color: #333;
      }
    }
  }
  
  .btn-container {
    margin-top: 60rpx;
    padding: 0 30rpx;
    
    .publish-btn {
      background-color: #07c160;
      color: #fff;
      border-radius: 50rpx;
      font-size: 32rpx;
      height: 90rpx;
      line-height: 90rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      &::after {
        border: none;
      }
    }
  }
}
</style>